package com.jjb.saas.demo.app.role.executor.command;
import com.alibaba.cola.dto.Response;
import com.jjb.saas.demo.domain.role.model.RoleE;
import com.jjb.saas.demo.infrastructure.queryservice.RoleQueryService;
import com.jjb.saas.framework.enums.enums.BooleanEnum;
import com.jjb.saas.system.client.role.request.RoleUpdateCmd;
import lombok.AllArgsConstructor;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import java.util.List;


/**
 * @author tzh * @date 2022年07月12日 20:26
 */
@AllArgsConstructor
@Component
public class RoleUpateExe {
    private final RoleQueryService roleQueryService;

    /**
     * 编辑
     * @param cmd
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public Response execute(RoleUpdateCmd cmd){
        RoleE roleE = RoleE.of(cmd.getId());
        roleE.setRoleName(cmd.getRoleName());
        roleE.setVersion(cmd.getVersion());
        roleE.setRoleTypeEnum(cmd.getRoleTypeEnum());
        List<Long> permsGroupIds = cmd.getPermsGroupIds();
        roleE.setPermsGroupIds(permsGroupIds);
        roleE.update();
        return Response.buildSuccess();
    }

    /**
     * 启用禁用
     * @param id
     * @param statusEnum
     * @return
     */
    @CacheEvict(value = "jjb-saas-system:role:user-dept",allEntries=true)
    @Transactional(rollbackFor = Exception.class)
    public Response execute(Long id,String statusEnum, Integer version){
        if(BooleanEnum.FALSE.getValue().equals(statusEnum)){
            Boolean b = roleQueryService.hasUsed(id);
            Assert.isTrue(!b,"角色被绑定请先解除");
        }
        RoleE roleE = RoleE.of(id);
        roleE.setStatusEnum(statusEnum);
        roleE.setVersion(version);
        roleE.updateSelf();
        return Response.buildSuccess();
    }
}
